package cn.szzsi.platform.controller.admin;

import cn.szzsi.business.controller.admin.BaseAdminController;
import cn.szzsi.common.bean.dto.CheckTreeNode;
import cn.szzsi.common.util.CommonUtil;
import cn.szzsi.model.*;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Created by yuanzheng on 2016/9/23.
 */
public class RoleController extends Controller {
    private PlatformRole platformRole;
    //private String shopId;
    // 列表
    public void list() {

        render(CommonUtil.TEMPLATE_PATH+"/platform/role/role_list.html");
    }
    //ajax list
    public void ajaxlist(){
        List<PlatformRole> lpr = PlatformRole.dao.find("select * from sys_platform_role order by createDate desc");
        renderJson(lpr);
    }

    // 添加
    public void add() {
        render(CommonUtil.TEMPLATE_PATH+"/platform/role/role_input.html");
    }

    // 编辑
    public void edit() {
        String id = getPara("id","");
        if (StrKit.notBlank(id)){
            setAttr("platformRole", PlatformRole.dao.findById(id));
        }
        render(CommonUtil.TEMPLATE_PATH+"/platform/role/role_input.html");
    }

    // 保存
    public void save() {
        platformRole = getModel(PlatformRole.class);
        platformRole.setId(CommonUtil.getUUID());
        platformRole.setCreateDate(new Date());
        platformRole.save();
        renderJson(Ret.ok("info","添加成功!").set("url","list"));
    }
    // 更新
    //@Before(BusinessRoleValidator.class)
    public void update() {
        platformRole = getModel(PlatformRole.class);
        platformRole.setModifyDate(new Date());
        platformRole.update();
        renderJson(Ret.ok("info","修改成功!").set("url","list"));
    }

    //角色的资源管理
    public void resource(){
        //展示出来
        setAttr("roleId",getPara("roleId"));
        setAttr("checked",true);
        render(CommonUtil.TEMPLATE_PATH+"/platform/role/role_resource.html");
    }

    @Before(Tx.class)
    public void resourceRoleSet(){

        String roleId = getPara("roleId");//角色id
        String resourceId = getPara("resourceId");//资源id(可能是动作ID)
        boolean checked = getParaToBoolean("checked");//是否选中
        boolean isParent=getParaToBoolean("isParent");//是否是树的父级

       // boolean isExsit = ActionResource.dao.isExsitByActionId(resourceId);//资源-动作是否存在
        if(checked){//选中(新增)
            PlatformResource platformResource= PlatformResource.dao.findById(resourceId);//当前菜单
            saveRoleResource(roleId,resourceId);//保存角色资源

            if(isParent){//如果是父级菜单
                //判断该父级菜单是否是伪父级菜单(即该菜单下面绑定了动作权限,相当于该菜单是子级菜单)
                setParentOrChildrenResource(platformResource,roleId);
            }else{//非父级菜单(1.可能是子级菜单下面的动作资源,2.可能是子级菜单)
         //子级菜单(下面不含有动作资源)
                    setParentResource(platformResource,roleId);

            }
        }else{//非选中(删除)
            PlatformRoleResource.dao.deleteByRoleAndResourceId(roleId,resourceId);//先删除当前菜单
            if(isParent){//如果是父级,将其下面的所有子菜单都删除
                PlatformResource parentRecourse= PlatformResource.dao.findById(resourceId);
                List<PlatformResource> listChildRecourse= PlatformResource.dao.getByPidOrCid(parentRecourse.getId().toString(),"");
                for(PlatformResource childRecourse:listChildRecourse){
                    PlatformRoleResource.dao.deleteByRoleAndResourceId(roleId,childRecourse.getId());

                }
            }
        }

        renderJson(true);
    }

    public void resourceTree(){
        //获取资源的id
        String id = getPara("id");
        String roleId = getPara("roleId");

        List<PlatformResource> lbr = PlatformResource.dao.getByPid(id,"");
        List<CheckTreeNode> lctn = new ArrayList<CheckTreeNode>();
        if(lbr.size()==0){//最后一级

        }else{
            for(PlatformResource br:lbr){
                CheckTreeNode ctn = new CheckTreeNode();
                ctn.setName(br.getStr("name"));
                ctn.setId(br.getId().toString());

                if(PlatformRoleResource.dao.isRoleResourceRalationExsit(br.getId(),roleId)){
                    ctn.setChecked(true);
                }else{
                    ctn.setChecked(false);
                }

                if(PlatformResource.dao.hasChildren(br.getId())){//父节点
                    ctn.setIsParent(true);
                }else{//子节点
                   //如果子节点不含有动作权限,则默认原来的子节点
                        ctn.setIsParent(false);
                }
                lctn.add(ctn);
            }
        }

        renderJson(lctn);
    }



    /**
     * 设置父级的role_resource(针对最后一级资源)
     * @param platformResource 父级资源对象
     * @param roleId 角色id
     */
    public void setParentResource(PlatformResource platformResource,String roleId){
        PlatformResource parentResource= PlatformResource.dao.findById(platformResource.getParentId());//父级角色
        PlatformResource pparentResource= PlatformResource.dao.findById(parentResource.getParentId());//父父级角色
        PlatformRoleResource pbrr = PlatformRoleResource.dao.getByRoleAndResourceId(roleId,parentResource.getId());//父级
        PlatformRoleResource ppbrr = PlatformRoleResource.dao.getByRoleAndResourceId(roleId,pparentResource.getId());//父父级
        if(pbrr==null){//如果父级没选择,则改变父级选中状态
            pbrr = new PlatformRoleResource();
            pbrr.set("roleId",roleId);
            pbrr.set("resourceId",parentResource.getId());
            pbrr.set("createDate",new Date());
            pbrr.save();
            if(ppbrr==null){
                ppbrr = new PlatformRoleResource();
                ppbrr.set("roleId",roleId);
                ppbrr.set("resourceId",pparentResource.getId());
                ppbrr.set("createDate",new Date());
                ppbrr.save();
            }

        }
    }

    /**
     *
     * @param platformResource 当前菜单
     * @param roleId 角色id
     */
    public void setParentOrChildrenResource(PlatformResource platformResource,String roleId){

        List<PlatformResource> listChildRecourse= PlatformResource.dao.getByPidOrCid(platformResource.getStr("path"),"");
        for(PlatformResource childRecourse:listChildRecourse){
            PlatformRoleResource newChildRoleRecourse=new PlatformRoleResource();
            newChildRoleRecourse.set("roleId",roleId);
            newChildRoleRecourse.set("resourceId",childRecourse.getId());
            newChildRoleRecourse.set("createDate",new Date());
            newChildRoleRecourse.save();
        }
        String parentId=platformResource.getStr("parent_id");//当前菜单的父级ID
        if(StrKit.notBlank(parentId)){//如果该父级菜单还有父级,将其父级也选中
            PlatformResource parentResource= PlatformResource.dao.findById(parentId);
            PlatformRoleResource pbrr = PlatformRoleResource.dao.getByRoleAndResourceId(roleId,parentResource.getId());
            if(pbrr==null){//如果父级没选择,则改变父级选中状态
                pbrr = new PlatformRoleResource();
                pbrr.set("roleId",roleId);
                pbrr.set("resourceId",parentResource.getId());
                pbrr.set("createDate",new Date());
                pbrr.save();
            }
        }
    }

    /**
     * 保存角色资源
     * @param roleId
     * @param resourceId
     */
    public void saveRoleResource(String roleId,String resourceId){
        PlatformRoleResource brr = new PlatformRoleResource();
        brr.set("roleId",roleId);
        brr.set("resourceId",resourceId);
        brr.set("createDate",new Date());
        brr.save();
    }



    // 删除
    public void delete() {
        String id=getPara("id");
        if(Admin.dao.isRelationRoleId(id)){
            renderJson(Ret.fail("info","删除成功,该角色已被其他用户关联!"));
            return;
        }
        PlatformRole.dao.deleteById(id);
        renderJson(Ret.ok());
        /*String[] ids = getParaValues("ids");
        if (ids != null && ids.length > 0) {
            for (String id : ids) {
                if (Role.dao.delete(id)) {
                    renderJson(Ret.ok("info","删除成功!"));

                } else {
                    renderJson(Ret.fail("info","删除失败!"));
                }
            }
        } else {
            renderJson(Ret.fail("info","id为空未选中，删除失败!"));
        }*/
    }
}
